package com.miao.elm.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miao.elm.dao.CartDao;
import com.miao.elm.entity.CartEntity;
import com.miao.elm.entity.FoodEntity;
import com.miao.elm.feign.FoodFeignClient;
import com.miao.elm.service.CartService;
import com.miao.elm.to.CartTo;
import com.miao.elm.to.FoodTo;
import com.miao.elm.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service("cartService")
public class CartServiceImpl extends ServiceImpl<CartDao, CartEntity> implements CartService {

    @Autowired
    CartDao cartDao;

    @Autowired
    FoodFeignClient foodFeignClient;

    @Override
    public List<FoodTo> listCartByInfo(CartTo cartTo) {
        QueryWrapper<CartEntity> wrapper = new QueryWrapper<CartEntity>().eq("user_id", cartTo.getUserId());
        if (cartTo.getBusinessId() != -1) {
            wrapper.eq("business_id", cartTo.getBusinessId());
        }
        List<CartEntity> cartEntities = this.baseMapper.selectList(wrapper);
        List<FoodTo> collect = cartEntities.stream().map(e -> {
            FoodTo foodTo = new FoodTo();
            BeanUtils.copyProperties(e, foodTo);
            R foodFeignResult = foodFeignClient.getFoodInfo(e.getFoodId());
            if (foodFeignResult.getCode() != 0) {
                foodTo.setFood(null);
                System.out.println("FoodFeign调用异常！");
            } else {
                foodTo.setFood(foodFeignResult.getData("food", new TypeReference<FoodEntity>() {
                }));
            }
            return foodTo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public int saveCart(CartTo cartTo) {
        CartEntity cartEntity = new CartEntity();
        BeanUtils.copyProperties(cartTo, cartEntity);
        System.out.println(cartEntity);
        return this.baseMapper.insert(cartEntity);
    }

    @Override
    public int updateCart(CartTo cartTo) {
        return cartDao.updateCart(cartTo);
    }

    @Override
    public int removeCart(CartTo cartTo) {
        if (cartTo.getFoodId() != -1) {
            return cartDao.removeCart(cartTo);
        }
        return this.baseMapper.delete(new QueryWrapper<CartEntity>().eq("user_id", cartTo.getUserId()).eq("business_id", cartTo.getBusinessId()));
    }
}